package com.rub.prajna.core

import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.util.regex.Matcher
import java.util.regex.Pattern


class AvExecutor {


    /**
     * 执行命令
     *
     * @param commands
     */
    suspend fun runCommand(commands: MutableList<String>): Boolean {
        try {
            val builder = ProcessBuilder()
            builder.command(commands)
            val p = builder.start()
            p.outputStream.close()
            p.inputStream.close()
            p.errorStream.close()
            if (p.waitFor() == 0) {
                println("runCommand success")
                return true
            }
            return false
        } catch (e: Exception) {
            System.err.printf("runCommand Exception " + e.message)
            return false
        }
    }

    /**
     * 获取视频总时间
     *
     * @param videoPath 视频路径
     * @return
     */
    fun getVideoTime(videoPath: String): Double? {
        val commands: MutableList<String> = ArrayList()
        commands.add(AvObject.ffmpegCommand)
        commands.add("-i")
        commands.add(videoPath)
        try {
            val builder = ProcessBuilder()
            builder.command(commands)
            val p = builder.start()
            p.waitFor()
            val sb = getFfmpegInfo(p)
            //从视频信息中解析时长
            val regexDuration = "Duration: (.*?), start: (.*?), bitrate: (\\d*) kb\\/s"
            val pattern: Pattern = Pattern.compile(regexDuration)
            val m: Matcher = pattern.matcher(sb.toString())
            if (m.find()) {
                val time = getTimelen(m.group(1))
                println("time=$time")
                return time
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return 0.0
    }

    /**
     * 获取ffmpeg信息
     *
     * @param p
     * @return
     * @throws IOException
     */
    @Throws(IOException::class)
    private fun getFfmpegInfo(p: Process): StringBuffer {
        //从输入流中读取视频信息
        val br = BufferedReader(InputStreamReader(p.errorStream))
        val sb = StringBuffer()
        var line: String? = ""
        while (br.readLine().also { line = it } != null) {
            sb.append(line)
        }
        br.close()
        return sb
    }

    /**
     * 格式:"00:00:10.68"
     *
     * @param timelen
     * @return
     */
    private fun getTimelen(timelen: String): Double {
        var min = 0.0
        val stress = timelen.split(":").toTypedArray()
        if (stress[0] > "0") {
            //秒
            min += java.lang.Double.valueOf(stress[0]) * 60 * 60
        }
        if (stress[1] > "0") {
            min += java.lang.Double.valueOf(stress[1]) * 60
        }
        if (stress[2] > "0") {
            min += java.lang.Double.valueOf(stress[2])
        }
        return min
    }
}